import { createStore } from 'vuex'
import store from 'storejs';
import { loginAPI } from "@/api/admin";


import auth from './modules/auth';


// console.log("store",store);
// console.dir(store);

// 存储数据(一条)
// store("user","a123123");
// store("pwd","123123");

// 存储数据(多条 => 整合到对象)
// store({user:"a123123",pwd:"123123"})
// console.log(store("user"));
// console.log(store("?user"));
// console.log(store());

// store(key,val)   => 了解
// store('info', (key,val) => {  // 存储数据时执行回调函数,回调函数的返回值就是存储的数据
//     console.log(key,val) // Processing the data obtained through the test here
//     return [3,4,5] // Return data and set store
// })

// store(key,val)  同时存搓个
// store(['name', 'pwd'], (key,val) => {
//     console.log('key:', key,val)
//     return '逐个更改数据'
//   })


// console.log(store("user123123"));


import routerJSON from '@/assets/json/routes.json';

// console.log("导入本地json", routerJSON);



// 创建一个新的 store 实例
const storeInstance = createStore({
    state: function () {
        return {
            authority: {
                adminname: null,
                checkedkeys: [],
                role: null,  // 1 2 3
                token: null,
            },
            isLoading:false,
        }
    },
    getters: {
        isLogin(state) {
            return !!(state.authority.adminname && state.authority.checkedkeys && state.authority.role && state.authority.token);
        },
        role(state){
            let roleList = ["super","admin","user"]; // 下标: 0 1 2
            return state.authority.role ?  roleList[ state.authority.role - 1] : null;
        }
    },
    mutations: {
        startLoading(state){
            state.isLoading = true;
        },
        endLoading(state){
            state.isLoading = false;
        },
        // store.commit("updateAuthority",data)
        updateAuthority(state, payload) {
            console.log("payload", payload);

            for (var key in payload) {
                // if (Object.hasOwn(state.authority, key)) {
                //     state.authority[key] = payload[key];
                // }

                if (Object.keys(state.authority).includes(key)) {
                    state.authority[key] = payload[key];
                }
                
            }
        },
        // 将Authority数据 存储到本地 localStorage
        setAuthorityToLocal(state, payload) {
            // localStorage.setItem("authority", JSON.stringify(payload));
            store.set("authority",payload);
        },
        getAuthorityFromLocal(state) {
            // let str = localStorage.getItem("authority");
            // if (str) {
            //     let authority = JSON.parse(str);
            //     for (var key in authority) {
            //         if (Object.hasOwn(state.authority, key)) {
            //             state.authority[key] = authority[key];
            //         }
            //     }
            // }

        
            let authority = store.get("authority");
            if (authority) {
                for (var key in authority) {
                    if (Object.hasOwn(state.authority, key)) {
                        state.authority[key] = authority[key];
                    }
                }
            }
        },
        removeAuthorityToLocal(){
            store.remove("authority");
        }
    },
    actions: {
        // 调用登录接口 登录成功  => 1. 更新authority  2. 本地存储(数据持久化)
        loginAndUpdateAuthority(context, data) {
            let { commit,dispatch } = context;
            return loginAPI(data).then(result => {  // 返回的还是Promise实例 后续可以接链式操作

                /* 模拟后端处理  对应角色信息,返回对应的权限配置项 */
                let roleList = ["super","admin","user"]; // 下标: 0 1 2
                let role = roleList[result.data.role-1];   // result.data.role => 1 2 3 

                let checkedkeys = routerJSON.filter(v=>v.meta.role.includes(role));

                console.log("2222--筛选后的权限菜单",checkedkeys);
                result.data.checkedkeys = checkedkeys;
                commit("updateAuthority", result.data);
                commit("setAuthorityToLocal", result.data);
                dispatch("getAuthMenu");
                return result;
            })
        },
        exitAndUpdateAuthority(context){
            let { commit } = context;
            commit("updateAuthority", {
                adminname: null,
                checkedkeys: null,
                role: null,
                token: null,
            });
            commit("removeAuthorityToLocal");
        }

    },
    modules:{
        auth
    }
})


export default storeInstance;